package bookshop.service;

import java.io.IOException;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import bookshop.DAO.BookDAOMapper;
import bookshop.DAO.WebOneSqlSession;
import bookshop.beans.Book;
import bookshop.beans.CriteriaBook;
import bookshop.beans.Page;

public class BookService {
	private BookDAOMapper bookMapper;
	private SqlSession session;
	private Page page;
	public BookService() {
		try {
			session=WebOneSqlSession.getSqlSession();
			bookMapper=session.getMapper(BookDAOMapper.class);
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
	//新增加一本书
	public void addBook(Book book) {
		bookMapper.addBook(book);
		session.commit();
	}
	//根据书名判断该书是否存在
	public boolean bookIsExist(String title) {
		Book book=bookMapper.query(title);
		if(book!=null) {
			return true;
		}
		return false;
	}
	//增加书的库存
	public void addBookStore(String title,int addNum) {
		bookMapper.addBookStore(title, addNum);
		session.commit();
	}
	public void getBooksByPrice(CriteriaBook criteria){
		int pageNo = criteria.getPageNo();
		int offset = (pageNo-1)*5;
		List<Book> books=bookMapper.queryForList(criteria.getMinPrice(), criteria.getMaxPrice(),offset);	
		page=new Page(pageNo);
		page.setList(books);
		page.setPageNo(pageNo);	
	}
	
	public void getTotalNum(CriteriaBook criteria) {
		int total=bookMapper.getSingleVal(criteria.getMinPrice(), criteria.getMaxPrice());
		page.setTotalItemNumber(total);
	}
	public Page getPage() {
		return page;
	}
}
